import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

import '../../Services/api_service.dart';
import '../../common/application.dart';
import '../../event/login_event.dart';
import '../../model/user_model.dart';
import '../../util/bubble_indication_painter.dart';
import '../../util/theme_util.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> with SingleTickerProviderStateMixin {
  Color themeColor = ThemeUtils.currentColorTheme;

  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  final FocusNode myFocusNodeEmailLogin = FocusNode();
  final FocusNode myFocusNodePasswordLogin = FocusNode();

  final FocusNode myFocusNodePassword = FocusNode();
  final FocusNode myFocusNodeName = FocusNode();

  TextEditingController loginEmailController = TextEditingController();
  TextEditingController loginPasswordController = TextEditingController();

  bool _obscureTextLogin = true;
  bool _obscureTextSignup = true;
  bool _obscureTextSignupConfirm = true;

  TextEditingController signupNameController = TextEditingController();
  TextEditingController signupPasswordController = TextEditingController();
  TextEditingController signupConfirmPasswordController = TextEditingController();

  late PageController _pageController;

  Color leftBtnColor = Colors.black;
  Color rightBtnColor = Colors.white;

  String title = "登录";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      key: _scaffoldKey,
      body: NotificationListener<OverscrollIndicatorNotification>(
         onNotification: (OverscrollIndicatorNotification notification) {
           notification.disallowIndicator(); // 禁用默认的overscroll效果
           return true; // 返回true表示通知已经被处理
         },
        child: SingleChildScrollView(
          child: Container(
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height >= 775.0 ? MediaQuery.of(context).size.height : 775.0,
            decoration: const BoxDecoration(
              gradient: LinearGradient(colors: [Color(0xFFffffff), Color(0xFFffffff)], begin: FractionalOffset(0.0, 0.0), end: FractionalOffset(1.0, 1.0), stops: [0.0, 1.0], tileMode: TileMode.clamp),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.max,
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.only(top: 60.0),
                  child: _buildMenuBar(context),
                ),
                Expanded(
                  flex: 2,
                  child: PageView(
                    controller: _pageController,
                    onPageChanged: (i) {
                      if (i == 0) {
                        setState(() {
                          rightBtnColor = Colors.white;
                          leftBtnColor = Colors.black;
                          title = "登录";
                        });
                      } else if (i == 1) {
                        setState(() {
                          rightBtnColor = Colors.black;
                          leftBtnColor = Colors.white;
                          title = "注册";
                        });
                      }
                    },
                    children: <Widget>[
                      ConstrainedBox(
                        constraints: const BoxConstraints.expand(),
                        child: _buildSignIn(context),
                      ),
                      ConstrainedBox(
                        constraints: const BoxConstraints.expand(),
                        child: _buildSignUp(context),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    myFocusNodePassword.dispose();
    myFocusNodeName.dispose();
    _pageController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();

    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);

    _pageController = PageController();
  }

  Widget _buildMenuBar(BuildContext context) {
    return Container(
      width: 300.0,
      height: 50.0,
      decoration: const BoxDecoration(
        color: Color(0x552B2B2B),
        borderRadius: BorderRadius.all(Radius.circular(25.0)),
      ),
      child: CustomPaint(
        painter: TabIndicationPainter(pageController: _pageController),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            Expanded(
              child: TextButton(
                onPressed: _onSignInButtonPress,
                child: Text(
                  "登录",
                  style: TextStyle(color: leftBtnColor, fontSize: 16.0),
                ),
              ),
            ),
            //Container(height: 33.0, width: 1.0, color: Colors.white),
            Expanded(
              child: TextButton(
                onPressed: _onSignUpButtonPress,
                child: Text(
                  "注册",
                  style: TextStyle(
                    color: rightBtnColor,
                    fontSize: 16.0,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSignIn(BuildContext context) {
    Future<void> login() async {
      String username = loginEmailController.text;
      String password = loginPasswordController.text;
      if ((username.trim().isNotEmpty) && (password.trim().isNotEmpty)) {
        ApiService().login(username, password, (UserModel userModel) {
          Application.eventBus.fire(LoginEvent());
          Fluttertoast.showToast(msg: "登录成功！");
          Navigator.of(context).pop();
        }, (String errMsg) {
           if (errMsg.isNotEmpty) {
             Fluttertoast.showToast(msg: errMsg);
           } else {
             Fluttertoast.showToast(msg: "登录失败");
           }
        });
      } else {
        Fluttertoast.showToast(msg: "用户名或者密码不能为空");
      }
    }

    return Container(
      padding: const EdgeInsets.only(top: 23.0),
      child: Column(
        children: <Widget>[
          Stack(
            alignment: Alignment.topCenter,
            children: <Widget>[
              Card(
                elevation: 0,
                color: Colors.white,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8.0),
                ),
                child: SizedBox(
                  height: 150.0,
                  child: Column(
                    children: <Widget>[
                      Padding(
                        padding: const EdgeInsets.only(top: 10.0, bottom: 10.0, left: 25.0, right: 25.0),
                        child: TextField(
                          focusNode: myFocusNodeEmailLogin,
                          controller: loginEmailController,
                          keyboardType: TextInputType.emailAddress,
                          style: const TextStyle(fontSize: 17.0, color: Colors.black),
                          decoration: const InputDecoration(
                              hintText: "用户名",
                              hintStyle: TextStyle(fontSize: 17.0),
                              icon: Icon(
                                FontAwesomeIcons.user,
                                color: Colors.black,
                                size: 22.0,
                              ),
                              filled: true,
                              fillColor: Color(0xFFF5F5F5),
                              isCollapsed: true,
                              contentPadding: EdgeInsets.symmetric(horizontal: 15, vertical: 15),
                              focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(50.0)), borderSide: BorderSide(color: Colors.white, width: 0)),
                              enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(50.0)), borderSide: BorderSide(color: Colors.white, width: 0)),
                              border: OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(50.0)), borderSide: BorderSide(color: Colors.white, width: 0))
                          ),
                        ),
                      ),

                      Padding(
                        padding: const EdgeInsets.only(top: 10.0, bottom: 0.0, left: 25.0, right: 25.0),
                        child: TextField(
                          focusNode: myFocusNodePasswordLogin,
                          controller: loginPasswordController,
                          obscureText: _obscureTextLogin,
                          style: const TextStyle(fontSize: 17.0, color: Colors.black),
                          decoration: InputDecoration(
                            hintText: "密码",
                            hintStyle: const TextStyle(fontSize: 17.0),
                            icon: const Icon(
                              FontAwesomeIcons.lock,
                              size: 22.0,
                              color: Colors.black,
                            ),
                            filled: true,
                            fillColor: const Color(0xFFF5F5F5),
                            isCollapsed: true,
                            contentPadding: const EdgeInsets.symmetric(horizontal: 15, vertical: 15),
                            focusedBorder: const OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(75.0)), borderSide: BorderSide(color: Colors.white, width: 0)),
                            enabledBorder: const OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(75.0)), borderSide: BorderSide(color: Colors.white, width: 0)),
                            border: const OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(75.0)), borderSide: BorderSide(color: Colors.white, width: 0)),
                            suffixIcon: GestureDetector(
                              onTap: _toggleLogin,
                              child: const Icon(
                                FontAwesomeIcons.eye,
                                size: 15.0,
                                color: Colors.black,
                              ),
                            ),
                          ),
                        ),
                      ),

                    ],
                  ),
                ),
              ),
              Container(
                margin: const EdgeInsets.only(top: 200.0),
                child: FilledButton(
                    style: FilledButton.styleFrom(shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)), backgroundColor: themeColor),
                    child: const Padding(
                      padding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 60.0),
                      child: Text(
                        "登录",
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 18.0,
                        ),
                      ),
                    ),
                    onPressed: () {
                      login();
                    }),
              ),
            ],
          )
        ],
      ),
    );
  }

  Widget _buildSignUp(BuildContext context) {
    Future<void> register() async {
      String username = signupNameController.text;
      String password = signupPasswordController.text;
      String rePassword = signupConfirmPasswordController.text;
      if ((username.trim().isNotEmpty) && (password.trim().isNotEmpty) && (rePassword.trim().isNotEmpty)) {
        if (password != rePassword) {
          Fluttertoast.showToast(msg: "两次密码输入不一致！");
        } else {
          ApiService().register(username, password, (UserModel userModel) {
            Application.eventBus.fire(LoginEvent());
            Fluttertoast.showToast(msg: "注册成功！");
            Navigator.of(context).pop();
          }, (String errMsg) {
            if (errMsg.isNotEmpty) {
              Fluttertoast.showToast(msg: errMsg);
            } else {
              Fluttertoast.showToast(msg: "注册失败");
            }
          });
        }
      } else {
        Fluttertoast.showToast(msg: "用户名或者密码不能为空");
      }
    }

    return Container(
      padding: const EdgeInsets.only(top: 23.0),
      child: Column(
        children: <Widget>[
          Stack(
            alignment: Alignment.topCenter,
            children: <Widget>[
              Card(
                elevation: 0.0,
                color: Colors.white,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8.0),
                ),
                child: SizedBox(
                  height: 220.0,
                  child: Column(
                    children: <Widget>[
                      Padding(
                        padding: const EdgeInsets.only(top: 10.0, bottom: 10.0, left: 25.0, right: 25.0),
                        child: TextField(
                          focusNode: myFocusNodeName,
                          controller: signupNameController,
                          keyboardType: TextInputType.text,
                          textCapitalization: TextCapitalization.words,
                          style: const TextStyle(fontSize: 17.0, color: Colors.black),
                          decoration: const InputDecoration(
                            hintText: "用户名",
                            hintStyle: TextStyle(fontSize: 17.0),
                            icon: Icon(
                              FontAwesomeIcons.user,
                              color: Colors.black,
                              size: 22.0,
                            ),
                            filled: true,
                            fillColor: Color(0xFFF5F5F5),
                            isCollapsed: true,
                            contentPadding: EdgeInsets.symmetric(horizontal: 15, vertical: 15),
                            enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(75.0)), borderSide: BorderSide(color: Colors.white, width: 0)),
                            border: OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(75.0)), borderSide: BorderSide(color: Colors.white, width: 0)),
                          ),
                        ),
                      ),

                      Padding(
                        padding: const EdgeInsets.only(top: 10.0, bottom: 10.0, left: 25.0, right: 25.0),
                        child: TextField(
                          focusNode: myFocusNodePassword,
                          controller: signupPasswordController,
                          obscureText: _obscureTextSignup,
                          style: const TextStyle(fontSize: 17.0, color: Colors.black),
                          decoration: InputDecoration(
                            hintText: "密码",
                            hintStyle: const TextStyle(fontSize: 17.0),
                            icon: const Icon(
                              FontAwesomeIcons.lock,
                              color: Colors.black,
                              size: 22.0,
                            ),
                            filled: true,
                            fillColor: const Color(0xFFF5F5F5),
                            isCollapsed: true,
                            contentPadding: const EdgeInsets.symmetric(horizontal: 15, vertical: 15),
                            enabledBorder: const OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(75.0)), borderSide: BorderSide(color: Colors.white, width: 0)),
                            border: const OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(75.0)), borderSide: BorderSide(color: Colors.white, width: 0)),
                            suffixIcon: GestureDetector(
                              onTap: _toggleSignup,
                              child: const Icon(
                                FontAwesomeIcons.eye,
                                size: 15.0,
                                color: Colors.black,
                              ),
                            ),
                          ),
                        ),
                      ),

                      Padding(
                        padding: const EdgeInsets.only(top: 10.0, bottom: 0, left: 25.0, right: 25.0),
                        child: TextField(
                          controller: signupConfirmPasswordController,
                          obscureText: _obscureTextSignupConfirm,
                          style: const TextStyle(fontSize: 17.0, color: Colors.black),
                          decoration: InputDecoration(
                            hintText: "确认密码",
                            hintStyle: const TextStyle(fontSize: 17.0),
                            icon: const Icon(
                              FontAwesomeIcons.lock,
                              color: Colors.black,
                              size: 22.0,
                            ),
                            filled: true,
                            fillColor: const Color(0xFFF5F5F5),
                            isCollapsed: true,
                            contentPadding: const EdgeInsets.symmetric(horizontal: 15, vertical: 15),
                            enabledBorder: const OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(75.0)), borderSide: BorderSide(color: Colors.white, width: 0)),
                            border: const OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(75.0)), borderSide: BorderSide(color: Colors.white, width: 0)),
                            suffixIcon: GestureDetector(
                              onTap: _toggleSignupConfirm,
                              child: const Icon(
                                FontAwesomeIcons.eye,
                                size: 15.0,
                                color: Colors.black,
                              ),
                            ),
                          ),
                        ),
                      ),

                    ],
                  ),
                ),
              ),
              Container(
                margin: const EdgeInsets.only(top: 250.0),
                decoration: const BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(5.0)),
                ),
                child: ElevatedButton(
                    style: ElevatedButton.styleFrom(shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)), backgroundColor: themeColor),
                    child: const Padding(
                      padding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 60.0),
                      child: Text(
                        "注册",
                        style: TextStyle(color: Colors.white, fontSize: 18.0),
                      ),
                    ),
                    onPressed: () {
                      register();
                    }),
              ),
            ],
          ),
        ],
      ),
    );
  }

  //切换到登录
  void _onSignInButtonPress() {
    _pageController.animateToPage(0, duration: const Duration(milliseconds: 500), curve: Curves.decelerate);
  }

  //切换到注册
  void _onSignUpButtonPress() {
    _pageController.animateToPage(1, duration: const Duration(milliseconds: 500), curve: Curves.decelerate);
  }

  //登录密码安全开关
  void _toggleLogin() {
    setState(() {
      _obscureTextLogin = !_obscureTextLogin;
    });
  }

  //注册密码安全开关
  void _toggleSignup() {
    setState(() {
      _obscureTextSignup = !_obscureTextSignup;
    });
  }

//注册确认密码安全开关
  void _toggleSignupConfirm() {
    setState(() {
      _obscureTextSignupConfirm = !_obscureTextSignupConfirm;
    });
  }
}
